package com.bk.action;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;

import com.bk.base.BaseServlet;
import com.bk.model.User;
import com.bk.utils.CommonsUtils;
import com.bk.utils.MD5Utils;
import com.bk.utils.SendJMail;

/**
 * 用户模块：登陆，注册 注销 ....
 * 登陆：login方法、注册：register方法 、注销：logOut方法
 * 问题：如何知道你访问的是哪个方法？？？？
 * localhost:8080/bk/userServlet?action=register======>访问注册
 * localhost:8080/bk/userServlet?action=login======>访问注登陆
 * localhost:8080/bk/userServlet?action=logOut======>注销注册
 */
public class UserServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
       
   
    public UserServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	protected void doGet1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
/*
		response.setContentType("text/html;charset=utf-8");
		String method = request.getParameter("action");
		//反射
		//servlet的class文件对象
		Class<? extends UserServlet> clz = this.getClass();
		//获得方法  方法名  参数
		try {
			Method m = clz.getDeclaredMethod(method,HttpServletRequest.class,HttpServletResponse.class );
			//执行方法invoke(obj, args)  obj：执行该方法的对象    args实际参数
			m.invoke(this,request,response );
			
		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			
			//TODO
			e.printStackTrace();
				
		}
		*/
		
		
		
		
		/*response.setContentType("text/html;charset=utf-8");
		String method = request.getParameter("action");
		if("login".equals(method)){
			login(request, response);
		}else if("register".equals(method)){
			
			register(request, response);
		}else if("logOut".equals(method)){
			logOut(request, response);
		}*/
		
		
		
		
		
	}
	
	protected void doPost1(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
/**
 * 登陆的逻辑
* @author: 千锋讲师张增强
* @createTime: 2017年7月3日 上午10:57:56
* @history:
* @param request
* @param response
* @throws ServletException
* @throws IOException void
 * @throws SQLException 
 */
	protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
		response.setContentType("text/json;charset=utf-8");
		String uname=request.getParameter("uname");
		String upwd=request.getParameter("upwd");
		String rem = request.getParameter("rememberMe");//on
		String auto = request.getParameter("autoLogin");//on
		
		User user=userServiceImpl.login(uname,upwd);
		
		
		Cookie c=new Cookie("username",uname);
		Cookie c1=new Cookie("upwd",upwd);
		Cookie c2=new Cookie("autoLogin",auto);
		
		
		if(user!=null){
			//用户名输入正确
			//response.getWriter().write("{\"flag\":\"yes\"}");
			//登陆成功
			if("on".equals(rem)){//勾选了记住我框
				//设置时长15天
				c.setMaxAge(15*24*3600);
				c1.setMaxAge(15*24*3600);
				
				
			}else{//登陆成功不想记录
				c.setMaxAge(0);
				c1.setMaxAge(0);
				
			}
			//存储cookie
			response.addCookie(c);
			response.addCookie(c1);	
			
			
			if("on".equals(auto)){
				c2.setMaxAge(15*24*3600);
				
				
			}
			response.addCookie(c2);

			request.getSession().setAttribute("user", user);
			request.getRequestDispatcher("index.jsp").forward(request, response);;
			
		}else{
			//错误
			response.getWriter().write("{\"flag\":\"no\"}");
		}

	}
/**
 * 注册的逻辑
* @author: 千锋讲师张增强
* @createTime: 2017年7月3日 上午10:58:06
* @history:
* @param request
* @param response
* @throws ServletException
* @throws IOException void
 * @throws InvocationTargetException 
 * @throws IllegalAccessException 
 * @throws SQLException 
 */
	protected void register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IllegalAccessException, InvocationTargetException, SQLException {
		Map<String, String[]> maps = request.getParameterMap();
		
		User u=new User();
		
		BeanUtils.populate(u, maps);
		
		//补全uid
		u.setUid(CommonsUtils.getUUID());
		u.setCode(CommonsUtils.getUUID());
		//密码加密  md5加密
		u.setUpwd(MD5Utils.md5(request.getParameter("upwd")));
		
		//调用service方法注册
		boolean flag=userServiceImpl.register(u);
		if(flag){
			//发送激活邮件
			String emailMsg="http://10.7.181.88:8080/"+request.getContextPath()+"/userServlet?uid="+u.getUid()+"&code="+u.getCode()+"&action=activeCode";
			SendJMail.sendMail(u.getUemail(), emailMsg);
			response.sendRedirect("registersuccess.jsp");
		}else{//注册失败
			request.setAttribute("error", "服务端异常，注册失败");
			request.getRequestDispatcher("register.jsp").forward(request, response);
			
		}
		
		
	
	}
/**
 * 注销的逻辑
* @author: 千锋讲师张增强
* @createTime: 2017年7月3日 上午10:58:14
* @history:
* @param request
* @param response
* @throws ServletException
* @throws IOException void
 */
	protected void logOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/**
		 * 把session销毁，跳转到主界面
		 */
		request.getSession().invalidate();
		//有自动登录的功能 把自动登录的cookie清除
		Cookie c=new Cookie("autoLogin","");
		c.setMaxAge(0);
		response.addCookie(c);
		//跳转到主界面
		response.sendRedirect("index.jsp");
		

	}
	/**
	 * ajax校验用户名是否存在
	 * @throws SQLException 
	 */
	protected void ajaxFindByName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
		response.setContentType("text/json;charset=utf-8");
		//获得用户名
		String uname = request.getParameter("uname");
		
		//调用service
		boolean flag=userServiceImpl.findByName(uname);
		if(flag){//用户名已经存在
			response.getWriter().write("{\"flag\":\"1\"}");
			
		}else{
			response.getWriter().write("{\"flag\":\"0\"}");

		}
		
	}
	/**
	 * ajax校验验证码是否正确
	 * @throws SQLException 
	 */
	protected void codeImageCheck(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
		response.setContentType("text/json;charset=utf-8");
		//获得用户名
		String code = request.getParameter("code");
		//
		String code_=(String) request.getSession().getAttribute("checkcode_session");
		
		//调用service
		
		if(code.equals(code_)){//验证码输入正确
			response.getWriter().write("{\"flag\":\"1\"}");
			
		}else{//验证码错误
			response.getWriter().write("{\"flag\":\"0\"}");

		}
		
	}
	protected void activeCode(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
		String uid = request.getParameter("uid");
		String code = request.getParameter("code");
		//根据uid去查询数据库
		boolean flag=userServiceImpl.active(uid,code);
		if(flag){
			//修改状态
			boolean flag_=userServiceImpl.active1(uid);
			if(flag_){//激活成功
				
				request.getRequestDispatcher("activesuccess.jsp").forward(request, response);
			}
			else{//激活失败
				request.getRequestDispatcher("registersuccess.jsp").forward(request, response);

				
			}
			
			
		}
		
		
	}
	
	
}
